<?php

namespace controller;

/**
 * Bazowa klasa kontrolera
 *
 * @author Damian Jóźwiak
 */
class Controller extends ControllerBase {
    protected  $shopURL=null;
    /**
     *<p>aktualnie wybrany sklep</p>
     * @var \model\TblShop
     */
    protected $shop=null;
    /**
     *
     * @var \model\TblPerson
     */
    protected  $person;
   protected function getRealIpAddr() {
        $ip = "";
        if (\library\RequestMethods::server('HTTP_CLIENT_IP')) {   //check ip from share internet
            $ip = \library\RequestMethods::server('HTTP_CLIENT_IP');
        } elseif (\library\RequestMethods::server('HTTP_X_FORWARDED_FOR')) {   //to check ip is pass from proxy
            $ip = \library\RequestMethods::server('HTTP_X_FORWARDED_FOR');
        } else {
            $ip = \library\RequestMethods::server('REMOTE_ADDR');
        }
        return $ip;
    }
    public function __construct($options = array()) {
        parent::__construct($options);
        date_default_timezone_set("Europe/Warsaw");
        $database = \library\Registry::get("database");
        $database->connect();
        $actionView = $this->getActionView();    
        $layoutView = $this->getLayoutView();
        $this->shopURL = \library\RequestMethods::get("shop","").',';
        if ($this->shopURL==","){
            $this->shop=null;
        }
        else {
            //pobranie sklepu
            $shopCriteria = new \model\Criteria();
            $shopCriteria->from(\model\TblShop::getModel()->getTable())->where(\model\TblShop::URL, "=", $this->shopURL);
            $this->shop= \model\TblShop::getModel()->first($shopCriteria);
            if (!$this->shop){
                throw new \model\exceptions\ShopNotExistsException($this->shopURL);
            }           
        }
          
        $session = \library\Registry::get("session");
        if ($session->get("login",false))  {
                $this->person = $session->get("login",false);
        }
        if ($this->willRenderActionView){
            $actionView->set("shop",  $this->shop);
            $actionView->set("shopurl",  $this->shopURL); 
            $actionView->set("person",  $this->person);   
        }
         if ($this->willRenderLayoutView){
             $layoutView->set("shop",  $this->shop);
            $layoutView->set("shopurl",  $this->shopURL);
            $layoutView->set("person",  $this->person);
         } 
         if ($this->shop){
              $session->set("shop",$this->shop);
         }
     }
    public function redirect($url,$slash=true){        
       if ($slash) {
           header("Location: /{$url}");
       }
       else {
           header("Location: {$url}");
       }
        exit();
    }

}
